<?php
namespace app\admin\controller;
use app\common\controller\Backend;
//use app\common\model\Category as CategoryModel;
use think\Facade\Cache;
use think\Controller;
use think\Request;
use fast\Tree;
use fast\Cols;
use fast\Random;

/**
 * 分类管理
 *
 * @icon fa fa-list
 * @remark 用于统一管理网站的所有分类,分类可进行无限级分类
 */
class Category extends Backend
{

    protected $model = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function initialize()
    {
        parent::initialize();
        $this->request->filter(['strip_tags']);
        $this->model = model('Category');
        $search = $this->request->get("search/a");

        if(isset($search)){
            $where = "%".$search['name']."%";
        }else{
            $where = "%%";
        }
        $tree = Tree::instance();
        $lst = $this->model->where('name','like',$where)->order('weigh desc,itemid desc')->select();
        if(isset($search)){
            $tree->init(collection($lst)->toArray());
            $this->categorylist = collection($lst)->toArray();
        }else{
            
            $tree->init(collection($lst)->toArray(), 'pid',' ');
            $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        }
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v)
        {
            $categorydata[$v['itemid']] = $v;
        }
        //$this->view->assign("flagList", $this->model->getFlagList());
        //$this->view->assign("typeList", CategoryModel::getTypeList());
        $modulelist = model('Module')->all();
        $this->view->assign("parentList", $categorydata);
        $this->view->assign("moduleList",$modulelist);
    }

    public function index(){
        $columnlist = Cols::columnread('column');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('pkey_name')){
            return $this->selectpage();
        }
        $searchfileds = array();
        $searchfileds['name'] = 'varcharmid';
        //$searchfileds['columnenname'] = 'varcharmid';
        $searchfileds['pid'] = 'int';

        $total = count($this->categorylist);
        $result = array("total" => $total, "rows" => $this->categorylist);

        $this->view->assign("lists",$result['rows']);
        $this->view->assign("listsjson",json_encode($result['rows']));
        $this->view->assign("columnlist",json_encode($columnlist));
        $this->view->assign("total",$result['total']);
        return $this->view->fetch();
    }
    public function add(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $category = \app\common\model\Category::create($params);
                    if ($category !== false){
                        $datacache = array();
                        $datacache['itemid'] = $category->itemid;
                        $datacache['name'] = $category->name; 
                        $datacache['diyname'] = $category->diyname;
                        cache('category'.$category->itemid,$datacache);
                        //添加成功
                        $this->success();
                    }else{
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            return $this->view->fetch();
        }
    }
    /**
     * 修改
     */
    public function edit($ids = NULL){
        $row = $this->model->get($ids);
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            if ($params){
                $this->modelValidate = false;
                if ($this->dataLimit){
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try{
                    //是否采用模型验证
                    if ($this->modelValidate){
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params,['itemid' => $ids]);
                    if ($result !== false){
                        $datacache = array();
                        $datacache['itemid'] = $ids;
                        $datacache['name'] = $params['name']; 
                        $datacache['diyname'] = $params['diyname'];
                        Cache::set('category'.$ids,$datacache);
                        //更新成功！
                        $this->success();
                    }else{
                        $this->error($row->getError());
                    }
                }
                catch (\think\exception\PDOException $e){
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            $row = $this->model->get($ids);
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
    }

    /**
     * 删除
     */
    public function del($ids = ""){
        if($ids){
            $model = $this->model->get($ids);
            $model->delete();
            Cache::rm('category'.$ids);
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 删除类别
     * @internal
     */
    public function dels(){
        if ($this->request->isPost()){
            $ids = $this->request->post("ids");
            $idarry = explode(',', $ids);
            foreach ($idarry as $k => $v) {
                if($v){
                    $model = $this->model->get($v);
                    $model->delete();
                    Cache::rm('category'.$v);
                }
            }
            $this->success();
            exit;
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
    /**
     * 获取类别列表
     * @internal
     */
    public function ajaxlist(){
        $ll = array();$llary = array();$arrwhere = array();$returnarry = array();
        if($this->request->post('moduleid')){
            $arrwhere[] = array('moduleid','eq',$this->request->post('moduleid'));
        }
        if($this->request->get('tree')){
                $llv = collection(model('Category')->where($arrwhere)->order('createtime', 'desc')->select())->toArray();
                Tree::instance()->init($llv);
                $ll = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(''), 'name');
        }else{
                $ll = collection(model('Category')->where($arrwhere)->order('createtime','desc')->select())->toArray();
        }
        if(count($ll)>0){
                print_r(json_encode($ll));exit;
        }else{
                print_r(json_encode($ll));exit;
        }
    }
}
